/*
============================================================================
 Name        : LockServerHelper.cpp
 Author      : DANG Zhengfa
 Version     :
 Copyright   : Zhengfa Company Limited
 Description : CLockServerHelper implementation
============================================================================
*/

#include "LockServerHelper.h"
#include "Shared.h"  // common variable between lockerserver(exe) & keylocker(app) & lockservRecongnizer(mdl)


#include <f32file.h> // for RFs, efsrv.lib 
#include <AknUtils.h> // For CompleteWithAppPath, avkon.lib eikcore.lib
#include <apgcli.h>  // For RApaLsSession, apgrfx.lib

// efsrv.lib  avkon.lib eikcore.lib apgrfx.lib

#if defined(__WINS__) // for WINS
	#include <e32math.h>
	static TBool gStarted = ETrue;
#endif

// constants for lodconfigurations
const TInt KBufferSize = 10;    // size of buffer to read and write parameter
_LIT8(KParameterFormat, "%-10d");  // format of buffer, write to file


TBool CLockServerHelper::StartLockServerL(void)
	{

#if defined(__WINS__) // for WINS
		gStarted = ETrue;
		return ETrue;
#endif

		// create file session
		RFs fs;
		User::LeaveIfError(fs.Connect());
		CleanupClosePushL(fs);
		
		// lock server path, without disk drive name
		TFileName appName(KLockServerPath);

		// find lockserver.exe
		TFindFile findFile(fs);
		User::LeaveIfError(findFile.FindByDir(appName,KNullDesC));

		// create apa session
		RApaLsSession ls;
		User::LeaveIfError(ls.Connect());
		CleanupClosePushL(ls);
		
		// create cmd
		CApaCommandLine *cmd = CApaCommandLine::NewLC();
		cmd->SetLibraryNameL(findFile.File());
		
		// KLockServerParameters is 16b descriptor, try to convert it into 8 bit ptr
		TPtrC para(KLockServerParameters);
		TPtrC8 para8( (TUint8*)para.Ptr(),para.Size() );
		cmd->SetTailEndL(para8);

		cmd->SetCommandL(EApaCommandRun);
		User::LeaveIfError(ls.StartApp(*cmd));

		// cleanup
		CleanupStack::PopAndDestroy(3); // cmd, ls, fs
		
		return ETrue;
	}

TBool CLockServerHelper::StopLockServerL(void)
	{

#if defined(__WINS__) // for WINS
		gStarted = EFalse;
		return ETrue;
#endif

		TFullName processName(KTextEXETitle);
		processName.Append(_L("*"));
		
		TFindProcess findProcess(processName);
		while ( findProcess.Next(processName) == KErrNone )
		{
			RProcess aProcess;
			TInt Err = aProcess.Open(findProcess, EOwnerProcess);
			if (Err == KErrNone)
			{
				aProcess.Kill(0);  // kill process
			}
			aProcess.Close();
		}
		
		return ETrue;
	}

TInt CLockServerHelper::CheckExistedServerL()
	{

#if defined(__WINS__) // for WINS
		return gStarted;
#endif

		TFullName processName(KTextEXETitle);
		processName.Append(_L("*"));
		
		TInt result = 0;
		TFindProcess findProcess(processName);
		while ( findProcess.Next(processName) == KErrNone )
		{
			result ++;
		}
		
		return result;
	}

TBool CLockServerHelper::LoadSettingFromFileL(const TUint &aVersion,TUint &aTimeInterval,TUint &aAutoStart,TUint &aEnableNote)
{
	TBool result = EFalse;

	// create file session
	RFs aSession;
	User::LeaveIfError(aSession.Connect());
	
	// get filename
	TFileName filename(KConfigureFile);
	CompleteWithAppPath(filename);

#if defined(__WINS__) // for WINS
	filename.Copy(_L("C:\\"));
	filename.Append(KConfigureFile);
#endif

	// open file
	RFile conFile;
	TInt err = conFile.Open(aSession, filename, EFileRead|EFileShareAny);

	TInt pos = 0;
	TBuf8<KBufferSize> buf;
	if (err == KErrNone)  // file exist
	{
		conFile.Seek(ESeekStart, pos);  // read from start
		
		TUint temp;
		TLex8 lex;
		
		// read parameters			
		conFile.Read(buf,buf.MaxSize());
		lex.Assign(buf);
		
		if(  lex.Val(temp) == KErrNone )
		{
			if ( aVersion == temp )  // version correct, load other parameters
			{
				conFile.Read(buf,buf.MaxSize());
				lex.Assign(buf);
				if(lex.Val(temp) == KErrNone) aTimeInterval = temp;

				conFile.Read(buf,buf.MaxSize());
				lex.Assign(buf);
				if(lex.Val(temp) == KErrNone) aAutoStart = temp;

				conFile.Read(buf,buf.MaxSize());
				lex.Assign(buf);
				if(lex.Val(temp) == KErrNone) aEnableNote = temp;

				result = ETrue;
			}
			else  // version incorrect, break;
			{
			}
		}
		else  // lex.val(temp) != KErrNone
		{
		}
	}
	else  // file doesn't exist
	{
	}
	
	// close resource
	conFile.Close();
	aSession.Close();

	return result;
}


TBool CLockServerHelper::SaveSettingToFileL(const TUint aVersion,TUint aTimeInterval,TUint aAutoStart,TUint aEnableNote)
{
	TBool result = EFalse;

	// create file session
	RFs theFS;
	User::LeaveIfError(theFS.Connect());

	// get filename
	TFileName fname(KConfigureFile);
	CompleteWithAppPath(fname);

#if defined(__WINS__) // for WINS
	fname.Copy(_L("C:\\"));
	fname.Append(KConfigureFile);
#endif

	// open file
	RFile theFile;
	TInt err = theFile.Open(theFS, fname, EFileWrite);
	if (err == KErrNotFound)  // file does not exist - create it
	{
		err = theFile.Create(theFS, fname, EFileWrite);
		if(err == KErrNone)  // create sucessfully
		{
			result = ETrue;
		}
	}
	else if(err == KErrNone)
	{
		result = ETrue;
	}

	if( result )
	{
		// now confile either exist, or has been created
		TInt pos = 0;
		theFile.Seek(ESeekStart,pos);

		TBuf8<KBufferSize> buf;
		buf.Format(KParameterFormat,aVersion);
		theFile.Write(buf,buf.MaxSize());
		
		buf.Format(KParameterFormat,aTimeInterval);
		theFile.Write(buf,buf.MaxSize());
		
		buf.Format(KParameterFormat,aAutoStart);
		theFile.Write(buf,buf.MaxSize());
		
		buf.Format(KParameterFormat,aEnableNote);
		theFile.Write(buf,buf.MaxSize());
	
	}
	
	// close resource
	theFile.Close();
	theFS.Close();
	return result;
}
